<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>

<script>

    
    // 情况一：没闭包（错误）
    var btns = document.getElementsByTagName('button');
    for (var i = 0; i < btns.length; i++)
    {
        btns[i].addEventListener('click', function ()
        {
            console.log("第"+ (i+1) + "个按钮被点击");
        })
    }


    // 情况二：使用闭包解决问题： 函数范围之内是有作用域的，传入1就是1不会被修改
    var btns = document.getElementsByTagName('button');
    for (var i = 0; i < btns.length; i++)
    {
        (function (i) {
            btns[i].addEventListener('click', function ()
            {
                console.log("第"+ (i+1) + "个按钮被点击");
            })
        })(i)
    }

    // 情况三：ES6写法
    const btns = document.getElementsByTagName('button');
    for (let i = 0; i < btns.length; i++)
    {
        btns[i].addEventListener('click', function()
        {
            console.log("第" + (i+1)+ "个按钮被点击");
        })
    }

</script>
    
</body>
</html>